# coding:utf-8
from functools import partial

from PyQt5.QtCore import Qt, QUrl, QSize
from PyQt5.QtWidgets import (QFrame, QHBoxLayout,
                             QHeaderView, QWidget, QVBoxLayout, QLabel,
                             QSpacerItem, QSizePolicy)
from qfluentwidgets import TableWidget, PushButton, SwitchButton, InfoBar, \
    InfoBarPosition, MessageBoxBase, SubtitleLabel, LineEdit, FluentIcon, ToolButton, TitleLabel, \
    TransparentPushButton, HyperlinkButton

from Users import UserManager
from common.style_sheet import StyleSheet
from common.translator import Translator
from utils.myutil import Globals
from .gallery_interface import GalleryInterface


class CustomMessageBox(MessageBoxBase):
    """ Custom message box """

    def __init__(self, str1, str2, parent=None):
        super().__init__(parent)
        self.titleLabel = SubtitleLabel(str1, self)
        self.urlLineEdit = LineEdit(self)

        self.urlLineEdit.setPlaceholderText(str2)
        self.urlLineEdit.setClearButtonEnabled(True)

        # add widget to view layout
        self.viewLayout.addWidget(self.titleLabel)
        self.viewLayout.addWidget(self.urlLineEdit)

        # change the text of button
        self.yesButton.setText('确定')
        self.cancelButton.setText('取消')

        self.widget.setMinimumWidth(350)
        self.yesButton.setDisabled(True)
        self.urlLineEdit.textChanged.connect(self._validateUrl)

        # self.hideYesButton()

    def _validateUrl(self, text):
        self.yesButton.setEnabled(QUrl(text).isValid())


class IdentifyControl(GalleryInterface):
    """ View interface """

    def __init__(self, parent=None):
        self.controller = parent.controller
        super().__init__(
            title="识别管理",
            subtitle="",
            parent=parent
        )
        self.setObjectName('Identifycontrol')

        self.ManageUserFrame = ManageIdentify(self)
        txt = self.tr('识别流管理')
        # table view
        self.addExampleCard(
            title=txt,
            widget=self.ManageUserFrame,
            sourcePath=''
        )

        self.ParaConfig = SetIdentify(self)
        txt = self.tr('参数配置')
        # table view
        self.addExampleCard(
            title=txt,
            widget=self.ParaConfig,
            sourcePath=''
        )


class SetIdentify(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        # Create the layout
        self.layout = QVBoxLayout(self)
        self.nowidentify = QLabel('当前识别流线程：0')
        self.layout.addWidget(self.nowidentify)
        self.hlayout = QHBoxLayout(self)

        self.button = PushButton("添加识别流")
        self.hlayout.addWidget(self.button)
        self.button = PushButton("执行全部识别")
        self.hlayout.addWidget(self.button)
        self.button = PushButton("终止全部识别")
        self.hlayout.addWidget(self.button)
        self.layout.addLayout(self.hlayout)

        self.table = TableWidget()
        self.layout.addWidget(self.table)
        self.setLayout(self.layout)

        self.table.verticalHeader().hide()
        self.table.setBorderRadius(8)
        self.table.setBorderVisible(True)
        self.manager = UserManager()

        self.table.setColumnCount(5)
        self.table.setRowCount(60)
        self.table.setHorizontalHeaderLabels(['视频流id', '识别预设', '识别流', '状态', '操作'])

        self.fill_table()

    def fill_table(self):
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.resizeColumnsToContents()
        self.table.setSortingEnabled(True)
        self.table.setRowCount(0)
        users = self.manager.get_users()  # Assuming get_users() returns a dictionary of users
        self.table.setRowCount(len(users))

        for i, user in enumerate(users.values()):
            # 名字
            videoid = QLabel(user.username)
            videoid_widget = QWidget()
            videoid_layout = QVBoxLayout()
            videoid_layout.addWidget(videoid)
            videoid_layout.setAlignment(Qt.AlignCenter)
            videoid_widget.setLayout(videoid_layout)
            self.table.setCellWidget(i, 0, videoid_widget)

            # 预设
            default = QLabel("交通")
            default_widget = QWidget()
            default_layout = QVBoxLayout()
            default_layout.addWidget(default)
            default_layout.setAlignment(Qt.AlignCenter)
            default_widget.setLayout(default_layout)
            self.table.setCellWidget(i, 1, default_widget)

            # 识别流
            stream_button = HyperlinkButton()
            stream_button.setIcon(FluentIcon.PLAY)
            stream_button.setText("查看")
            stream_button_widget = QWidget()
            stream_button_layout = QHBoxLayout()
            stream_button_layout.addWidget(stream_button)
            stream_button_layout.setAlignment(Qt.AlignCenter)
            stream_button_layout.setContentsMargins(0, 0, 0, 0)
            stream_button_widget.setLayout(stream_button_layout)
            self.table.setCellWidget(i, 2, stream_button_widget)

            # 状态
            state = QLabel("未识别")
            state.setStyleSheet("color: red;")
            state_widget = QWidget()
            state_layout = QVBoxLayout()
            state_layout.addWidget(state)
            state_layout.setAlignment(Qt.AlignCenter)
            state_widget.setLayout(state_layout)
            self.table.setCellWidget(i, 3, state_widget)

            # Action button
            edit_button = PushButton("配置")
            delete_button = PushButton("执行识别")
            stop_button = PushButton("终止识别")
            action_button_widget = QWidget()
            action_button_layout = QHBoxLayout()
            action_button_layout.addWidget(edit_button)
            action_button_layout.addWidget(delete_button)
            action_button_layout.addWidget(stop_button)
            action_button_layout.setAlignment(Qt.AlignCenter)
            action_button_layout.setContentsMargins(0, 0, 0, 0)
            action_button_widget.setLayout(action_button_layout)
            self.table.setCellWidget(i, 4, action_button_widget)

        self.table.setFixedSize(1200, 400)
        self.table.resizeColumnsToContents()


class ManageIdentify(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        # Create the layout
        self.layout = QVBoxLayout(self)
        self.nowidentify = QLabel('当前识别流线程：0')
        self.layout.addWidget(self.nowidentify)
        self.hlayout = QHBoxLayout(self)

        self.button = PushButton("添加识别流")
        self.hlayout.addWidget(self.button)
        self.button.clicked.connect(self.add_user)
        self.button = PushButton("执行全部识别")
        self.hlayout.addWidget(self.button)
        self.button.clicked.connect(self.add_user)
        self.button = PushButton("终止全部识别")
        self.hlayout.addWidget(self.button)
        self.button.clicked.connect(self.add_user)
        self.layout.addLayout(self.hlayout)

        self.table = TableWidget()
        self.layout.addWidget(self.table)
        self.setLayout(self.layout)

        self.table.verticalHeader().hide()
        self.table.setBorderRadius(8)
        self.table.setBorderVisible(True)
        self.manager = UserManager()

        self.table.setColumnCount(5)
        self.table.setRowCount(60)
        self.table.setHorizontalHeaderLabels(['视频流id', '识别预设', '识别流', '状态', '操作'])

        self.fill_table()

    def fill_table(self):
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.resizeColumnsToContents()
        self.table.setSortingEnabled(True)
        self.table.setRowCount(0)
        users = self.manager.get_users()  # Assuming get_users() returns a dictionary of users
        self.table.setRowCount(len(users))

        for i, user in enumerate(users.values()):
            # 名字
            videoid = QLabel(user.username)
            videoid_widget = QWidget()
            videoid_layout = QVBoxLayout()
            videoid_layout.addWidget(videoid)
            videoid_layout.setAlignment(Qt.AlignCenter)
            videoid_widget.setLayout(videoid_layout)
            self.table.setCellWidget(i, 0, videoid_widget)

            # 预设
            default = QLabel("交通")
            default_widget = QWidget()
            default_layout = QVBoxLayout()
            default_layout.addWidget(default)
            default_layout.setAlignment(Qt.AlignCenter)
            default_widget.setLayout(default_layout)
            self.table.setCellWidget(i, 1, default_widget)

            # 识别流
            stream_button = HyperlinkButton()
            stream_button.setIcon(FluentIcon.PLAY)
            stream_button.setText("查看")
            stream_button.clicked.connect(partial(self.edit_user, user.username))
            stream_button_widget = QWidget()
            stream_button_layout = QHBoxLayout()
            stream_button_layout.addWidget(stream_button)
            stream_button_layout.setAlignment(Qt.AlignCenter)
            stream_button_layout.setContentsMargins(0, 0, 0, 0)
            stream_button_widget.setLayout(stream_button_layout)
            self.table.setCellWidget(i, 2, stream_button_widget)

            # 状态
            state = QLabel("未识别")
            state.setStyleSheet("color: red;")
            state_widget = QWidget()
            state_layout = QVBoxLayout()
            state_layout.addWidget(state)
            state_layout.setAlignment(Qt.AlignCenter)
            state_widget.setLayout(state_layout)
            self.table.setCellWidget(i, 3, state_widget)

            # Action button
            edit_button = PushButton("配置")
            edit_button.clicked.connect(partial(self.edit_user, user.username))
            delete_button = PushButton("执行识别")
            delete_button.clicked.connect(partial(self.delete_user, user.username))
            stop_button = PushButton("终止识别")
            stop_button.clicked.connect(partial(self.edit_user, user.username))
            action_button_widget = QWidget()
            action_button_layout = QHBoxLayout()
            action_button_layout.addWidget(edit_button)
            action_button_layout.addWidget(delete_button)
            action_button_layout.addWidget(stop_button)
            action_button_layout.setAlignment(Qt.AlignCenter)
            action_button_layout.setContentsMargins(0, 0, 0, 0)
            action_button_widget.setLayout(action_button_layout)
            self.table.setCellWidget(i, 4, action_button_widget)

        self.table.setFixedSize(1200, 400)
        self.table.resizeColumnsToContents()

    def set_admin(self, username, state):
        try:
            w = CustomMessageBox('修改权限', '请输入超级管理员密码:', self.parent().parent().parent().parent().parent())
            if w.exec():
                if not self.manager.check_password('superadmin', w.urlLineEdit.text()):
                    content = "超级管理员密码错误"
                    InfoBar.error(
                        title='Error!',
                        content=content,
                        orient=Qt.Horizontal,
                        isClosable=True,
                        position=InfoBarPosition.BOTTOM_RIGHT,
                        # position='Custom',   # NOTE: use custom info bar manager
                        duration=2000,
                        parent=self.parent().parent().parent().parent()
                    )
                    # Reset the switch
                    state.blockSignals(True)
                    state.setChecked(not state.isChecked())
                    state.blockSignals(False)
                else:
                    self.manager.set_admin(username, state.isChecked())
                    content = f"用户 {username} 现在是 {'管理员' if state.isChecked() else '普通用户'}。"
                    InfoBar.success(
                        title='成功！',
                        content=content,
                        orient=Qt.Horizontal,
                        isClosable=True,
                        position=InfoBarPosition.BOTTOM_RIGHT,
                        # position='Custom',   # NOTE: use custom info bar manager
                        duration=2000,
                        parent=self.parent().parent().parent().parent()
                    )
            else:
                # Reset the switch
                state.blockSignals(True)
                state.setChecked(not state.isChecked())
                state.blockSignals(False)
        except Exception as e:
            content = f"修改用户 {username} 的权限时发生错误：{str(e)}"
            InfoBar.error(
                title='Error!',
                content=content,
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.BOTTOM_RIGHT,
                # position='Custom',   # NOTE: use custom info bar manager
                duration=2000,
                parent=self.parent().parent().parent().parent()
            )

    def delete_user(self, username):
        try:
            self.manager.delete_user(username)
            content = f"用户 {username} 已被删除。"
            InfoBar.success(
                title='成功！',
                content=content,
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.BOTTOM_RIGHT,
                # position='Custom',   # NOTE: use custom info bar manager
                duration=2000,
                parent=self.parent().parent().parent().parent()
            )
            self.fill_table()
        except Exception as e:
            content = f"删除用户 {username} 时发生错误：{str(e)}"
            InfoBar.error(
                title='Error!',
                content=content,
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.BOTTOM_RIGHT,
                # position='Custom',   # NOTE: use custom info bar manager
                duration=2000,
                parent=self.parent().parent().parent().parent()
            )

    def edit_user(self, username):
        try:
            if self.manager.check_admin(username):
                w = CustomMessageBox('修改密码', '请输入超级管理员密码:',
                                     self.parent().parent().parent().parent().parent())
                if w.exec():
                    if self.manager.check_password('superadmin', w.urlLineEdit.text()):
                        # 弹出输入新密码对话框
                        w = CustomMessageBox('修改密码', '请输入新密码:',
                                             self.parent().parent().parent().parent().parent())
                        if w.exec():
                            self.manager.change_password(username, w.urlLineEdit.text())
                            content = f"用户 {username} 的密码已被修改。"
                            InfoBar.success(
                                title='成功！',
                                content=content,
                                orient=Qt.Horizontal,
                                isClosable=True,
                                position=InfoBarPosition.BOTTOM_RIGHT,
                                # position='Custom',   # NOTE: use custom info bar manager
                                duration=2000,
                                parent=self.parent().parent().parent().parent()
                            )
                    else:
                        content = "超级管理员密码错误"
                        InfoBar.error(
                            title='Error!',
                            content=content,
                            orient=Qt.Horizontal,
                            isClosable=True,
                            position=InfoBarPosition.BOTTOM_RIGHT,
                            # position='Custom',   # NOTE: use custom info bar manager
                            duration=2000,
                            parent=self.parent().parent().parent().parent()
                        )
            else:
                w = CustomMessageBox('修改密码', '请输入新密码:', self.parent().parent().parent().parent().parent())
                if w.exec():
                    self.manager.change_password(username, w.urlLineEdit.text())
                    content = f"用户 {username} 的密码已被修改。"
                    InfoBar.success(
                        title='成功！',
                        content=content,
                        orient=Qt.Horizontal,
                        isClosable=True,
                        position=InfoBarPosition.BOTTOM_RIGHT,
                        # position='Custom',   # NOTE: use custom info bar manager
                        duration=2000,
                        parent=self.parent().parent().parent().parent()
                    )
        except Exception as e:
            content = f"修改用户 {username} 的密码时发生错误：{str(e)}"
            InfoBar.error(
                title='Error!',
                content=content,
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.BOTTOM_RIGHT,
                # position='Custom',   # NOTE: use custom info bar manager
                duration=2000,
                parent=self.parent().parent().parent().parent()
            )

    def add_user(self):
        try:
            w = CustomMessageBox('添加用户', '请输入用户名:', self.parent().parent().parent().parent().parent())
            if w.exec():
                username = w.urlLineEdit.text()
                w = CustomMessageBox('添加用户', '请输入密码:', self.parent().parent().parent().parent().parent())
                if w.exec():
                    password = w.urlLineEdit.text()
                    w = CustomMessageBox('添加用户', '请再次输入密码:',
                                         self.parent().parent().parent().parent().parent())
                    if w.exec():
                        if password != w.urlLineEdit.text():
                            raise Exception('两次密码不一致')
                        is_admin = False
                        if Globals.user is not None and self.manager.check_admin(Globals.user.username):
                            w = CustomMessageBox('添加为管理员', '输入超级管理员密码(非管理员输入“否”)',
                                                 self.parent().parent().parent().parent().parent())
                            if w.exec():
                                if self.manager.check_password('superadmin', w.urlLineEdit.text()):
                                    is_admin = True
                        self.manager.add_user(username, password, is_admin)
                        content = f"用户 {username} 已被添加。"
                        InfoBar.success(
                            title='成功！',
                            content=content,
                            orient=Qt.Horizontal,
                            isClosable=True,
                            position=InfoBarPosition.BOTTOM_RIGHT,
                            # position='Custom',   # NOTE: use custom info bar manager
                            duration=2000,
                            parent=self.parent().parent().parent().parent()
                        )
                        self.fill_table()
        except Exception as e:
            content = f"添加用户时发生错误：{str(e)}"
            InfoBar.error(
                title='Error!',
                content=content,
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.BOTTOM_RIGHT,
                # position='Custom',   # NOTE: use custom info bar manager
                duration=2000,
                parent=self.parent().parent().parent().parent()
            )
